/**
 * 
 */
package com.leoj.utils.tcp_network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * @author leoj
 *
 */
public class TcpConnection {
	private Socket _sock;
	private ObjectInputStream _input;
	private ObjectOutputStream _output;
	
	/**
	 * @throws IOException 
	 * 
	 */
	public TcpConnection(Socket socket) throws IOException {
		_sock = socket;
		_input = new ObjectInputStream(_sock.getInputStream());
		_output = new ObjectOutputStream(_sock.getOutputStream());
	}
	public TcpConnection(String address, int port) throws IOException {
		this(new InetSocketAddress(address, port));
	}
	public TcpConnection(InetAddress address, int port) throws IOException {
		this(new InetSocketAddress(address, port));
	}
	public TcpConnection(SocketAddress address) throws IOException{
		_sock = new Socket();
		System.out.println("binding the TcpConnection");
		_sock.connect(address);
		System.out.println("connected");
		System.out.println("creating OutputObjectStream");
		_output = new ObjectOutputStream(_sock.getOutputStream());
		System.out.println("creating inputObjectStream");
		_input = new ObjectInputStream(_sock.getInputStream());
	}
	
	public void send(Object m) throws IOException{
		_output.writeObject(m);
		_output.flush();
	}
	public Object read() throws IOException, ClassNotFoundException{
		return _input.readObject();
	}
	public InetAddress getInetAddress(){
		return _sock.getInetAddress();
	}
	/**
	 * @throws IOException 
	 * 
	 */
	public void close() throws IOException {
		_sock.close();
	}
}
